package com.oig.sys.msg.im.handler.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.ContentType;
import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.google.common.base.Throwables;
import com.oig.common.util.JsonUtil;
import com.oig.sys.msg.constants.MsgEnums;
import com.oig.sys.msg.im.domain.account.FeiShuRobotAccount;
import com.oig.sys.msg.im.domain.feishu.FeiShuRobotParam;
import com.oig.sys.msg.im.domain.feishu.FeiShuRobotResult;
import com.oig.sys.msg.im.handler.BaseHandler;
import com.oig.sys.msg.vo.NoticeMsgVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * 企业微信群机器人 消息处理器
 */
@Slf4j
@Component
public class FeiShuRobotHandler extends BaseHandler {

    public FeiShuRobotHandler() {
        channelCode = MsgEnums.MsgChannel.FEI_SHU_ROBOT.getCode() + MsgEnums.MsgChannel.FEI_SHU_ROBOT.getNoticeTypeCode();
    }

    @Override
    public boolean handler(NoticeMsgVo noticeMsg) {
        try {
            FeiShuRobotAccount account = JsonUtil.toObject(noticeMsg.getChannelConfig(), FeiShuRobotAccount.class);
            FeiShuRobotParam feiShuRobotParam = assembleParam(noticeMsg);
            String result = HttpRequest.post(account.getWebhook())
                    .header(Header.CONTENT_TYPE.getValue(), ContentType.JSON.getValue())
                    .body(JSON.toJSONString(feiShuRobotParam))
                    .timeout(2000)
                    .execute().body();
            FeiShuRobotResult feiShuRobotResult = JSON.parseObject(result, FeiShuRobotResult.class);
            if (feiShuRobotResult.getStatusCode() == 0) {
                return true;
            }
            log.error("FeiShuRobotHandler#handler fail! result:{},params:{}", JSON.toJSONString(feiShuRobotResult), JSON.toJSONString(noticeMsg));
        } catch (Exception e) {
            log.error("FeiShuRobotHandler#handler fail!e:{},params:{}", Throwables.getStackTraceAsString(e), JSON.toJSONString(noticeMsg));
        }
        return false;
    }

    private FeiShuRobotParam assembleParam(NoticeMsgVo noticeMsg) {
        FeiShuRobotParam param = FeiShuRobotParam.builder().msgType("text").build();
        String content = noticeMsg.getContent();
        if (content.contains("@")) {
            String userId = StrUtil.subAfter(content, "@", true);
            if (StrUtil.isNotBlank(userId)) {
                String at = " <at user_id=\"{}\"></at>";
                at = StrUtil.format(at, userId);
                content = StrUtil.subBefore(content, "@", true);
                content = content + at;
            }
        }
        param.setContent(FeiShuRobotParam.ContentDTO.builder().text(content).build());
        return param;
    }

}

